package com.caochenlei.controller;

import com.caochenlei.domain.CloudStorageConfig;
import com.caochenlei.domain.ResponseVo;
import com.caochenlei.domain.UploadResponse;
import com.caochenlei.utils.MD5Utils;
import com.caochenlei.utils.QCloudUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController()
@Api(tags = "上传文件接口")
public class UploadController {
    @Value("${spring.application.name}")
    private String appName;
    @Value("${qcloud.scretId}")
    private String scretId;
    @Value("${qcloud.secretKey}")
    private String secretKey;
    @Value("${qcloud.region}")
    private String region;
    @Value("${qcloud.bucketName}")
    private String bucketName;
    @Value("${qcloud.domain}")
    private String domain;

    @ResponseBody
    @PostMapping(value = "/upload")
    @ApiOperation(value = "上传文件")
    @Secured({"ROLE_ADMIN"})
    public UploadResponse upload(
            @ApiParam(name = "file", value = "上传文件对象", required = true)
            @RequestParam(value = "file") MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            log.error("上传文件不能为空！");
            throw new RuntimeException("上传文件不能为空！");
        }
        try {
            String originalFileName = file.getOriginalFilename();
            String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();
            CloudStorageConfig cloudStorageConfig = new CloudStorageConfig();
            cloudStorageConfig.setQcloudSecretId(scretId);
            cloudStorageConfig.setQcloudSecretKey(secretKey);
            cloudStorageConfig.setQcloudRegion(region);
            cloudStorageConfig.setQcloudBucketName(bucketName);
            cloudStorageConfig.setQcloudDomain(domain);
            cloudStorageConfig.setQcloudPrefix(appName);
            String dir = cloudStorageConfig.getQcloudPrefix();
            String md5 = MD5Utils.getMessageDigest(file.getBytes());
            String filePath = String.format("%1$s/%2$s%3$s", dir, md5, suffix);
            log.info("上传文件路径：{}", filePath);
            ResponseVo responseVo = QCloudUtils.writeFile(cloudStorageConfig, filePath, file);
            String qCloudDomain = cloudStorageConfig.getQcloudDomain();
            String url = String.format("%1$s/%2$s", qCloudDomain, filePath);
            if (responseVo.getStatus().equals(200)) {
                return new UploadResponse(filePath.substring(appName.length() + 1), originalFileName, file.getSize(), suffix, url, 200, "文件上传成功！");
            } else {
                return new UploadResponse(originalFileName, 500, responseVo.getMsg());
            }
        } catch (Exception e) {
            log.error(String.format("UploadController.upload%s", e));
            throw e;
        }
    }
}
